<!-- 购物车 -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车--书瞳</title>
    <link rel="icon" href="__ROOT__/public/lcbook.ico" type="image/x-icon">
    <link rel="stylesheet" href="__ROOT__/public/static/css/common.css">
    <link rel="stylesheet" href="__ROOT__/public/static/css/header.css">
    <link rel="stylesheet" href="__ROOT__/public/static/css/cartnav.css">
    <link rel="stylesheet" href="__ROOT__/public/static/css/cart.css">
    <link rel="stylesheet" href="__ROOT__/public/static/css/emptyMsg.css">

    <!-- fontawesome字体 -->
    <link rel="stylesheet" href="__ROOT__/public/static/font/font-awesome.min.css">
</head>

<body>
    <!-- 头部 -->
    {include file="./public/common/header.html"/}

    <!-- 中间logo部分 -->
    <div id="nav">
        <div class="navBox">
            <div class="logo">
          		<a href="{:url('index/index')}">
                <img src="__ROOT__/public/static/image/logo.png" alt=""></a>
            </div>
            <span class="title">购物车</span>
            <ul class="bar">
                <li class="lichoose">我的购物车</li>
                <li>填写订单</li>
                <li>完成订单</li>
            </ul>
        </div>
    </div>

    <!-- 购物车 -->
    <div id="cart">
        {if condition="$count != 0"}
        <div class="cartBox">
            <!-- 上面部分 -->
            <div class="up">
                <ul>
                    <li><a href="{:url('index/index')}">
                            < </a>
                    </li>
                    <li>商品信息</li>
                    <li>单价/元</li>
                    <li>数量</li>
                    <li>金额</li>
                    <li>操作</li>
                </ul>

                <!-- 商品 -->
                <!-- 
                    sum  --》 现价
                    total --》 原价
                    count --》 已选购商品数量
                 -->
                {assign name="sum" value="0" /}
                {assign name="total" value="0" /}
                {foreach $result as $cart}
                {assign name="sum" value="$sum + $cart.yourprice * $cart.num" /}
                {assign name="total" value="$total + $cart.price * $cart.num" /}
                <!-- 计算购物车条目 -->
                <ul class="shop mt12" id="shop{$cart.cartID}">
                    <li class="aicenter"><input type="checkbox" class="chk" name='cartID[]' value='{$cart.cartID}'
                            checked onclick="chk(this)" /></li>
                    <li class="jcstart f333"><a href="{:url('shopdetail/shopdetail')}">
                    <img src="__ROOT__/public/static/image/{$cart.pictures}" alt=""></a>
                    <span class="mt12"><a href="{:url('shopdetail/shopdetail')}">
                    {$cart.bname}</a></span></li>

                    <!-- 现价 -->
                    <li class="cartyourPrice mt12">￥{$cart.yourprice}</li>
                    <!-- 原价 -->
                    <li class="cartPrice displayNone">￥{$cart.price}</li>

                    <!-- 数量按钮 -->
                    <li class="mt12 btnBox">
                        <span style="display: none;">{$cart.bookID}</span>
                        <span style="display: none;">{$cart.cartID}</span>
                        <button class="subShop">-</button>
                        <div>
                            <input type="text" value="{$cart.num}" name='num' id='{$cart.bookID}' class="updShop">
                        </div>
                        <button class="addShop">+</button>
                    </li>

                    <li class="mt12 f333 shopSum">￥{$cart.yourprice*$cart.num}</li>

                    <!-- 操作 -->
                    <li class="mt12 caozuo">
                        <p><a href='{:url("star/addStar")}?bookID={$cart.bookID}'>移入收藏</a></p>
                        <p><a href='#' onclick="deleteCart('{$cart.cartID}')">删除</a></p>
                    </li>
                </ul>
                {/foreach}

                <!-- 下面部分 -->
                <div class="down">
                    <p><input id="selectAll" checked type="checkbox" class="vamiddle" onclick="chkAll()" />全选</p>
                    <p><a href="#" class="f333" id="delMore">批量删除</a></p>
                    <p class="taleft">已选择<span class="activate_font">1</span>件商品</p>
                    <div class="priceBox">
                        <p>
                            <span>总计（不含运费）：</span>
                            <span id="sumPrice" class="activate_font fs20">￥{$sum}</span>
                        </p>

                        <p>
                            <span>已节省：</span>
                            <span id="yhPrice">￥{$total-$sum}</span>
                        </p>
                    </div>
                    <a href="#" class="toCorder"><button>结算</button></a>
                </div>
            </div>
        </div>
        <div id="empty" class="displayNone">
            <!-- <div id="empty"> -->
            <img src="__ROOT__/public/static/image/empty.png" alt="">
            <div>
                <h4 class="tit">您的购物车为空哦！</h4>
                <p class="msg"><a href="{:url('index/index')}" class="activate_font">去随便逛逛吧，</a>看有没有喜欢的</p>
            </div>
        </div>

        {else /}
        <!-- 购物车为空时显示 -->
        <div id="empty">
            <!-- <div id="empty"> -->
            <img src="__ROOT__/public/static/image/empty.png" alt="">
            <div>
                <h4 class="tit">您的购物车为空哦！</h4>
                <p class="msg"><a href="{:url('index/index')}" class="activate_font">去随便逛逛吧，</a>看有没有喜欢的</p>
            </div>
        </div>
        {/if}
        <!-- js代码 -->
        <script src="__ROOT__/public/static/js/jquery-1.8.3.min.js"></script>
        <script src="__ROOT__/public/static/js/header.js"></script>
        <script>
            /*****
             * 更新
             * 选择、删除：只需要更新总价 + 优惠金额
             * 数量: 更新物品的金额 + 总价格 + 优惠金额
             * 移入收藏：只需要更新总价 + 优惠金额
             * **/

            // 商品前面的按钮
            function chk(ele) {
                // console.log($(ele).prop('checked'));
                let status = $(ele).prop('checked');
                if (status) {

                } else {
                    $('#selectAll').prop('checked', false);//全选状态取消
                }
                updateSum();
            }

            //全选按钮被选中
            //当全选按钮的状态为checked时，所有商品选中；否则，无视
            function chkAll() {
                if ($('#selectAll').prop('checked')) {
                    $('.chk').prop('checked', true);
                    updateSum();
                }
            }


            //更新总价
            function updateSum() {
                let sum = 0;//现总价
                let total = 0;//原总价
                //遍历所有的商品，如果checked，就把其价格加起来
                $('.shop').each(function () {
                    //判断是否选中
                    let chk = $(this).children('li:first').children('.chk').prop('checked');
                    if (!chk) return;

                    //获取原价、现价、购买数量
                    let price = parseFloat($(this).children('.cartPrice').text().substring(1));
                    let yourprice = parseFloat($(this).children('.cartyourPrice').text().substring(1));
                    let num = parseInt($(this).children('.btnBox').children('div').children('.updShop').val());
                    sum += yourprice * num;
                    total += price * num;
                });

                $('#sumPrice').text('￥' + sum.toFixed(2));
                $('#yhPrice').text('￥' + (total - sum).toFixed(2));
            }

            //通知更新某件商品的总价格
            function updateShop($ele) {
                let yourprice = parseFloat($ele.children('.cartyourPrice').text().substring(1));
                let num = parseInt($ele.children('.btnBox').children('div').children('.updShop').val());
                $ele.children('.shopSum').text("￥" + (yourprice * num).toFixed(2));
            }

            $(function () {
                // 添加商品的按钮被点击
                $('.addShop').click(function () {
                    let obj = getArguments($(this));
                    $.post('{:url("cart:Plus")}', obj, function (res) {
                        if (res == "ok") { //成功
                            $('#' + obj.bookID).val(parseInt($('#' + obj.bookID).val()) + 1);
                            updateShop($('#' + obj.bookID).parent().parent().parent());//通知更新某件商品
                            updateSum();
                        } else { //失败
                            alert("服务器繁忙~~");
                        }
                    });

                });

                //减少商品的按钮被点击
                $('.subShop').click(function () {

                    let obj = getArguments($(this));
                    if ($('#' + obj.bookID).val() == 1) {
                        alert("不能再减喽！");
                        return;
                    }
                    $.post('{:url("cart:Minus")}', obj, function (res) {
                        if (res == "ok") { //成功
                            $('#' + obj.bookID).val(parseInt($('#' + obj.bookID).val()) - 1);
                            updateShop($('#' + obj.bookID).parent().parent().parent());//通知更新某件商品
                            updateSum();
                        } else { //失败
                            alert("服务器繁忙~~");
                        }
                    });
                });

                // 更新数量input框失去焦点
                $('.updShop').blur(function () {
                    let obj = getArguments($(this).parent());
                    let num = parseInt($('#' + obj.bookID).val());
                    if (isNaN(num) || num <= 0) {
                        alert("请输入>0合法的数字！！！");
                        $('#' + obj.bookID).val(1);
                        updateShop($('#' + obj.bookID).parent().parent().parent());//通知更新某件商品
                        updateSum();
                        return;
                    }

                    obj.num = num;
                    $.post('{:url("cart:updateCart")}', obj, function (res) {
                        if (res == "ok") { //成功
                            updateShop($('#' + obj.bookID).parent().parent().parent());//通知更新某件商品
                            updateSum();
                        } else { //失败
                            alert("服务器繁忙~~");
                            $('#' + obj.bookID).val(1);
                        }
                    });

                });

                //批量删除的按钮被点击
                $('#delMore').click(function () {
                    if (confirm("被勾选的宝贝都会被删除！您确定要继续吗？")) {
                        // alert("确定");
                        let cartIDs = [];
                        $('.shop').each(function () {
                            let chk = $(this).children('li:first').children('.chk').prop('checked');
                            if (chk) cartIDs.push($(this).children('li:first').children('.chk').val());
                        });
                        // console.log(cartIDs);
                        $.post('{:url("cart/deleteMore")}', {
                            cartIDs: cartIDs
                        }, function (res) {
                            window.location.href = "{:url('cart/cart')}";
                        });
                    }
                });
                
                //结算按钮被点击
               $('.toCorder').click(function () {
                // if (confirm("被勾选的宝贝都会被删除！您确定要结算吗？")) {
                	let cartIDs = [];
                    $('.shop').each(function () {
                        let chk = $(this).children('li:first').children('.chk').prop('checked');
                        if (chk) cartIDs.push($(this).children('li:first').children('.chk').val());
                    });
                    window.location.href = `__ROOT__/index/corder/corder?cartIDs=${cartIDs}`;
                    /* console.log(cartIDs);
                	$.post('{:url("corder/corder")}',{
                		'cartIDs': cartIDs
                	},function (res){
                		// alert(cartIDs);
                		window.location.href = `__ROOT__/index/corder/corder`;
                	}); */
               	//  }
            	});
          });

            function getArguments($obj) {
                // 获取商品的ID
                let bookID = $obj.parent().children(':first').text();
                let cartID = $obj.parent().children(':first').next().text();
                return {
                    bookID: bookID,
                    cartID: cartID
                };
            }

            //删除商品按钮被点击
            function deleteCart(cartID) {
                $.get('{:url("cart:deleteCart")}', { cartID: cartID }, function (res) {
                    if (res == "ok") { //成功
                        if ($('#shop' + cartID).parent().children().length == 3) {
                            console.log($('#empty').get(0));
                            // 已经没有商品
                            $('#empty').removeClass('displayNone');
                            $('.cartBox').hide();

                            return;
                        }
                        $('#shop' + cartID).remove();
                        updateSum();

                    } else { //失败
                        alert("删除失败");
                    }
                });
            }

        </script>

</body>

</html>